package com.aidansmeaton.weightmanager.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import android.util.Log;

/**
 * This class provides utility functions for formatting
 * time strings, such as ISO-8601 format into a
 * "human readable" format, and vice versa.
 * 
 * @author Aidan Smeaton
 */
public class TimeFormatter {
	
	public static String getMonthAsString(int monthInt){
		switch (monthInt){
		case 0:	return "Jan";
		case 1: return "Feb";
		case 2: return "Mar";
		case 3: return "Apr";
		case 4: return "May";
		case 5: return "Jun";
		case 6: return "Jul";
		case 7: return "Aug";
		case 8: return "Sep";
		case 9: return "Oct";
		case 10: return "Nov";
		case 11: return "Dec";
		default: return "?"+monthInt;
		}
	}

	public static String getDayAsString(int dayInt) {
		switch (dayInt){
		case 1:	return "Sun";
		case 2: return "Mon";
		case 3: return "Tue";
		case 4: return "Wed";
		case 5: return "Thu";
		case 6: return "Fri";
		case 7: return "Sat";
		default: return "?"+dayInt;
		}
	}

	public static String getDatabaseDateString(Calendar c) {
		int y = c.get(Calendar.YEAR);
		int m = c.get(Calendar.MONTH)+1;
		int d = c.get(Calendar.DAY_OF_MONTH);
		return y+"-"+(m<10 ? "0":"")+m+"-"+(d<10 ? "0":"")+d;
	}
	
	public static String getTimeAsString(String databaseString, boolean includeSeconds){
		return databaseString.substring(databaseString.indexOf(" "),databaseString.indexOf(":")+ ((includeSeconds) ? 6 : 3));
	}
	
	public static String getDatetimeNow(){
		return (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(new java.util.Date());
	}
	
	public static String getWeekBoundary(String originalDate, boolean firstDay){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date d;
		try {
			d = sdf.parse(originalDate);
		} catch (ParseException e) {
			e.printStackTrace();
			return originalDate;
		}
        Calendar c = Calendar.getInstance();
        c.setTime(d);
        
        int day = 0;
        switch (c.get(Calendar.DAY_OF_WEEK)){
        case	Calendar.MONDAY:	day = 0;	break;
        case	Calendar.TUESDAY:	day = 1;	break;
        case	Calendar.WEDNESDAY:	day = 2;	break;
        case	Calendar.THURSDAY:	day = 3;	break;
        case	Calendar.FRIDAY:	day = 4;	break;
        case	Calendar.SATURDAY:	day = 5;	break;
        case	Calendar.SUNDAY:	day = 6;	break;
        }
        
        if (firstDay) c.add(Calendar.DATE, (0-day));
        else c.add(Calendar.DATE, (6-day));
        
        return getDatabaseDateString(c);
	}
	
}
